﻿using System;
using System.Web;
using System.Web.Security;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Account
{
    public partial class ResetPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            pnl_ResetPassword.Visible = false;
            pnl_ResetPasswordSucces.Visible = false;

            UserService svc = new UserService();
            string resetPasswordUrl = (Request.QueryString["ResetPasswordUrl"] != null) ? Server.HtmlEncode(Request.QueryString["ResetPasswordUrl"]) : String.Empty;

            if (Session["ResetPasswordSuccesful"] != null)
            {
                pnl_ResetPasswordSucces.Visible = true;
                UserNameLabel.Text = HttpContext.Current.User.Identity.Name;
            }
            else if (resetPasswordUrl.Length > 0)
            {
                ResetPasswordURL url = svc.GetResetPasswordUrlByUrl(resetPasswordUrl);
                if (url != null)
                {
                    pnl_ResetPassword.Visible = true;
                    Password.Focus();
                    pnl_ResetPassword.DefaultButton = "ResetPasswordButton";
                }
                else
                {
                    Response.Redirect("~/Default.aspx"); //gebruiker zit te prutsen met strings
                }
            }
            else
            {
                Response.Redirect("~/Default.aspx"); //gebruiker heeft hier niks te zoeken
            }
        }

        protected void ResetPasswordClick(object sender, EventArgs e)
        {
            string pass = Server.HtmlEncode(Password.Text);
            string salt = EncryptionUtils.Salt();
            string hash = EncryptionUtils.Hash(pass, salt);

            UserService svc = new UserService();

            string resetPasswordUrl = (Request.QueryString["ResetPasswordUrl"] != null) ? Server.HtmlEncode(Request.QueryString["ResetPasswordUrl"]) : String.Empty;
            ResetPasswordURL url = svc.GetResetPasswordUrlByUrl(resetPasswordUrl);

            User user = svc.GetUserById(url.UserId);
            user.Hash = hash;
            user.Salt = salt;
            svc.UpdateUser(user);

            svc.RemoveResetPasswordUrl(url);

            Session["ResetPasswordSuccesful"] = true;
            FormsAuthentication.SetAuthCookie(user.Name, false);
            Response.Redirect(Request.Url.AbsoluteUri);
        }
    }
}